<template>
  <div class="contract-search-container">
    <TitleBar title="合约查询" />
    <div class="contract-search-window">
      <!-- 搜索框和工具栏 -->
      <div class="search-container">
        <div class="search-input-wrapper">
          <Input
            v-model:value="searchKeyword"
            placeholder="搜索合约代码"
            size="large"
            class="search-input"
            @input="handleSearch"
            :disabled="isLoading"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </Input>
        </div>

        <!-- 工具栏 -->
        <div class="toolbar">
          <button
            class="refresh-btn"
            @click="forceRefresh"
            :disabled="isLoading"
          >
            <LoadingOutlined v-if="isLoading" class="loading-icon" />
            <span v-else>🔄</span>
          </button>
        </div>
      </div>

      <!-- 合约列表 -->
      <div class="contract-list-container">
        <div class="contract-header">
          <div
            class="header-item contract-code sortable"
            :class="{ active: sortBy === 'code' }"
            @click="handleSort('code')"
          >
            合约代码
          </div>
        </div>

        <div class="contract-content">
          <!-- 按分类显示合约 -->
          <div
            v-for="category in filteredCategories"
            :key="category.code"
            class="contract-category"
          >
            <!-- <div class="category-header">
              <span class="category-name">{{ category.name }}({{ category.code }})</span>
              <span class="category-count">{{ category.contracts.length }}个合约</span>
            </div> -->

            <div class="category-contracts">
              <div
                v-for="contract in category.contracts"
                :key="contract.code"
                class="contract-item"
                :class="{ selected: selectedContract?.code === contract.code }"
                @click="selectContract(contract)"
                @dblclick="openContractPanel(contract)"
              >
                <div class="contract-code">{{ contract.code }}</div>
              </div>
            </div>
          </div>

          <!-- 无搜索结果 -->
          <div
            v-if="filteredCategories.length === 0 && !isLoading"
            class="no-results"
          >
            <Empty description="未找到匹配的合约" />
          </div>

          <!-- 加载中 -->
          <div v-if="isLoading" class="loading-container">
            <div class="loading-content">
              <LoadingOutlined class="loading-icon" />
              <div class="loading-text">正在加载合约数据...</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { SearchOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import { Empty, Input } from "ant-design-vue";
import { emit } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import type { ContractInfo, ContractCategory } from "@/types/trading";
import { useContractStore } from "@/stores/contractStore";
import { contractService } from "@/services/contractService";
import TitleBar from "@/components/TitleBar.vue";

// 响应式数据
const searchKeyword = ref("");
const selectedContract = ref<ContractInfo | null>(null);
const allCategories = ref<ContractCategory[]>([]);
const priceUpdateInterval = ref<number | null>(null);
const isLoading = ref(false);
const totalContractsCount = ref(0);
const sortBy = ref<"code" | "name" | "price" | "change">("code");
const sortOrder = ref<"asc" | "desc">("asc");
const quickFilter = ref("");
const isFromCache = ref(false); // 标识数据是否来自缓存
const cacheInfo = ref<any>(null); // 缓存信息

// 动态获取的品种分类（从CTP数据中提取）
const popularCategories = computed(() => {
  // 显示所有分类作为快速筛选
  return allCategories.value.map((category) => ({
    code: category.code,
    name: category.name,
  }));
});

// 合约状态管理
const { setCurrentContract } = useContractStore();

// 计算属性
const filteredCategories = computed(() => {
  let categories = allCategories.value;

  // 快速过滤
  if (quickFilter.value) {
    categories = categories.filter(
      (category) =>
        category.code.toUpperCase() === quickFilter.value.toUpperCase()
    );
  }

  // 搜索过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase().trim();

    categories = categories
      .map((category) => ({
        ...category,
        contracts: category.contracts.filter(
          (contract) =>
            contract.code.toLowerCase().includes(keyword) ||
            contract.name.toLowerCase().includes(keyword) ||
            contract.category.toLowerCase().includes(keyword) ||
            contract.categoryCode.toLowerCase().includes(keyword) ||
            contract.fullCode.toLowerCase().includes(keyword)
        ),
      }))
      .filter((category) => category.contracts.length > 0);
  }

  // 排序
  return categories.map((category) => ({
    ...category,
    contracts: sortContracts(category.contracts),
  }));
});

// 计算过滤后的合约总数
const filteredContractsCount = computed(() => {
  return filteredCategories.value.reduce((total, category) => {
    return total + category.contracts.length;
  }, 0);
});

// 排序合约列表
const sortContracts = (contracts: ContractInfo[]) => {
  return [...contracts].sort((a, b) => {
    let aValue: any, bValue: any;

    switch (sortBy.value) {
      case "code":
        aValue = a.code;
        bValue = b.code;
        break;
      case "name":
        aValue = a.name;
        bValue = b.name;
        break;
      case "price":
        aValue = a.lastPrice || 0;
        bValue = b.lastPrice || 0;
        break;
      case "change":
        aValue = a.changePercent || 0;
        bValue = b.changePercent || 0;
        break;
      default:
        return 0;
    }

    if (typeof aValue === "string") {
      const result = aValue.localeCompare(bValue);
      return sortOrder.value === "asc" ? result : -result;
    } else {
      const result = aValue - bValue;
      return sortOrder.value === "asc" ? result : -result;
    }
  });
};

// 处理排序
const handleSort = (field: "code" | "name" | "price" | "change") => {
  return;
  // if (sortBy.value === field) {
  //   // 如果点击的是当前排序字段，切换排序方向
  //   sortOrder.value = sortOrder.value === "asc" ? "desc" : "asc";
  // } else {
  //   // 如果点击的是新字段，设置为升序
  //   sortBy.value = field;
  //   sortOrder.value = "asc";
  // }
};

// 设置快速过滤
const setQuickFilter = (categoryCode: string) => {
  quickFilter.value = categoryCode;
  // 清除搜索关键词，避免冲突
  if (categoryCode) {
    searchKeyword.value = "";
  }
};

// 方法
const handleSearch = () => {
  // 搜索时清除选择和快速过滤
  selectedContract.value = null;
  if (searchKeyword.value.trim()) {
    quickFilter.value = "";
  }
};

const selectContract = (contract: ContractInfo) => {
  selectedContract.value = contract;
  openContractPanel(contract);
};

const openContractPanel = async (contract: ContractInfo | null) => {
  if (!contract) {
    return;
  }


  try {
    // 设置当前选中的合约
    setCurrentContract(contract);
    // 创建包含priceTick的合约选择事件数据
    const contractWithPriceTick = {
      ...contract,
      priceTick: contract.priceTick, // 如果没有priceTick，将在useMarketData中生成默认值
    };

    // 发送合约选择事件到主窗口，包含priceTick信息
    await emit("contract-selected", contractWithPriceTick);

    // 关闭搜索窗口
    // closeWindow()
  } catch (error) {
  }
};

const closeWindow = async () => {
  try {
    const currentWindow = getCurrentWindow();
    await currentWindow.close();
  } catch (error) {
  }
};

// 刷新合约数据（不订阅行情）
const refreshContractData = async () => {
  try {
    // 只刷新合约数据，不订阅行情
    allCategories.value = contractService.getAllCategoriesSync();
  } catch (error) {
  }
};

// 初始化合约数据
const initializeContractData = async () => {
  try {
    isLoading.value = true;

    // 获取缓存信息
    cacheInfo.value = await contractService.getCacheInfo();

    // 记录初始化前的状态，用于判断数据来源
    const wasInitialized = contractService.isDataInitialized();

    allCategories.value = await contractService.getAllCategories();

    // 判断数据来源 - 使用服务提供的准确信息
    const dataSource = contractService.getLastDataSource();
    isFromCache.value = dataSource === "cache";


    // 计算总合约数
    totalContractsCount.value = allCategories.value.reduce(
      (total, category) => {
        return total + category.contracts.length;
      },
      0
    );

    // 更新缓存信息
    cacheInfo.value = await contractService.getCacheInfo();
  } catch (error) {

    // 即使初始化失败，也要尝试显示缓存状态
    const dataSource = contractService.getLastDataSource();
    isFromCache.value = dataSource === "cache";

    allCategories.value = [];
    totalContractsCount.value = 0;
  } finally {
    isLoading.value = false;
  }
};

// 生命周期
// 强制刷新合约数据
const forceRefresh = async () => {
  try {
    isLoading.value = true;

    // 强制重新初始化，这会优先从 CTP API 获取最新数据
    await contractService.forceReinitialize();

    // 重新加载数据
    allCategories.value = await contractService.getAllCategories();

    // 计算总合约数
    totalContractsCount.value = allCategories.value.reduce(
      (total, category) => {
        return total + category.contracts.length;
      },
      0
    );

    // 标记为来自网络（因为是强制刷新）
    isFromCache.value = false;

    // 更新缓存信息
    cacheInfo.value = await contractService.getCacheInfo();

  } catch (error) {

    // 刷新失败时，检查是否使用了缓存
    const dataSource = contractService.getLastDataSource();
    isFromCache.value = dataSource === "cache";
  } finally {
    isLoading.value = false;
  }
};

onMounted(async () => {
  // 初始化数据
  await initializeContractData();

  // 刷新合约数据（不订阅行情）
  refreshContractData();
});

onUnmounted(() => {});
</script>

<style scoped lang="less">
.contract-search-container {
  height: 100vh;
  background-color: #0d1117;
}

.contract-search-window {
  padding: 4px;
  background-color: #0d1117;
  color: #c9d1d9;
  height: calc(100% - 32px);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  gap: 4px;

  .search-container {
    display: flex;
    gap: 8px;
    align-items: center;

    .search-input-wrapper {
      flex: 1;

      .search-input {
        border-radius: 6px;
        border-color: #30363d;
        color: #c9d1d9;
        /* height: 24px; */
        padding: 0 5px;

        :deep(.ant-input) {
          color: #c9d1d9;
          border-radius: 10px;
        }

        :deep(.ant-input-prefix) {
          color: #8b949e;
        }
      }
    }

    .refresh-btn {
      background: #21262d;
      border: 1px solid #30363d;
      color: #c9d1d9;
      border-radius: 4px;
      padding: 4px 8px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover:not(:disabled) {
        background: #30363d;
        border-color: #58a6ff;
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }

      .loading-icon {
        animation: spin 1s linear infinite;
      }
    }
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .contract-list-container {
    flex: 1;
    border: 1px solid #30363d;
    border-radius: 6px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .contract-header {
      display: flex;
      background: #161b22;
      border-bottom: 1px solid #30363d;
      padding: 4px;
      font-weight: 600;
      color: #c9d1d9;
    }

    .contract-content {
      flex: 1;
      overflow-y: auto;
      background-color: #0d1117;
      /* 隐藏滚动条但保持滚动功能 */
      &::-webkit-scrollbar {
        width: 0px; /* 隐藏滚动条 */
        background: transparent; /* 透明背景 */
      }

      &::-webkit-scrollbar-track {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: transparent;
      }

      .contract-category {
        .category-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 8px 16px;
          background: #161b22;
          border-bottom: 1px solid #30363d;
          font-weight: 500;
          color: #8b949e;

          .category-name {
            font-size: 14px;
          }

          .category-count {
            font-size: 12px;
            color: #8b949e;
          }
        }

        .category-contracts {
          .contract-item {
            display: flex;
            align-items: center;
            padding: 8px 16px;
            border-bottom: 1px solid #21262d;
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
              background: #161b22;
            }

            &.selected {
              background: #1f6feb33;
              border-color: #1f6feb;
            }

            .contract-checkbox {
              width: 20px;
              margin-right: 8px;
            }

            .contract-code {
              width: 100%;
              font-weight: 500;
              color: #c9d1d9;
            }
          }
        }
      }

      .no-results {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;
        color: #8b949e;
      }

      .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;

        .loading-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 12px;
          color: #8b949e;

          .loading-icon {
            font-size: 24px;
            animation: spin 1s linear infinite;
          }

          .loading-text {
            font-size: 14px;
          }
        }
      }
    }
  }
}
</style>
